์บ์ฑ ์ ๋ต
- ์บ์ ์ ์ค : ์บ์์ ์ ๊ทผํ์ ๋ ์ฐพ๊ณ ์๋ ๋ฐ์ดํฐ๊ฐ ์๋ ๊ฒฝ์ฐ
- ์บ์ ๋๋ฝ : ์บ์์ ์ ๊ทผํ์ ๋ ์ฐพ๊ณ ์๋ ๋ฐ์ดํฐ๊ฐ ์๋ ๊ฒฝ์ฐ
- ์ญ์ ์ ์ฑ
: ์บ์์ ๊ณต๊ฐ์ด ๋ถ์กฑํ ๋ ๊ณต๊ฐ์ ํ๋ณดํ๋ ๋ฐฉ๋ฒ
Cache-Aside
- Lazy Loading, ๋ฐ์ดํฐ๋ฅผ ์กฐํํ ๋ ํญ์ ์บ์๋ฅผ ๋จผ์ ํ์ธํ๋ ์ ๋ต
- ํ์ ๋ฐ์ดํฐ๋ง ์บ์์ ๋ณด๊ด
- ์ต์ด ์กฐํ์ ์บ์ ํ์ธ์ ์ํด ์๊ฐ์ด ์๋์ ์ผ๋ก ์ค๋ ๊ฑธ๋ฆผ
Write-Through
- ๋ฐ์ดํฐ ์์ฑ ์ ํญ์ ์บ์์ ์์ฑํ๊ณ ์๋ณธ์๋ ์์ฑํ๋ ์ ๋ต
- ์บ์์ ๋ฐ์ดํฐ ์ํ๊ฐ ํญ์ ์ต์ ์์ ๋ณด์ฅ
- ์์ฃผ ์ฌ์ฉํ์ง ์๋ ๋ฐ์ดํฐ๋ ์บ์์ ์ค๋ณตํด์ ์ ์ฅ โ ์๊ฐ์ด ์ค๋ ๊ฑธ๋ฆผ
Write-Behind
- ์บ์์๋ง ๋ฐ์ดํฐ๋ฅผ ์์ฑํ๊ณ ์ผ์ ์ฃผ๊ธฐ๋ก ์๋ณธ์ ๊ฐฑ์ ํ๋ ๋ฐฉ์
- ์บ์ ๋ฐ์ดํฐ๊ฐ ์๋ณธ์ ์ ์ฉํ๊ธฐ ์ ๋ฌธ์ ๊ฐ ๋ฐ์ํ๋ฉด ๋ฐ์ดํฐ ์์ค๋ ์ํ์ฑ O
Spring Cache
CacheConfig
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
// CacheManager๋ก ์งํํด๋ ์ ์ ๋์
public RedisCacheManager cacheManager(
RedisConnectionFactory redisConnectionFactory
) {
// ์ค์ ๊ตฌ์ฑ์ ๋จผ์ ์งํํ๋ค.
// Redis๋ฅผ ์ด์ฉํด์ Spring Cache๋ฅผ ์ฌ์ฉํ ๋
// Redis ๊ด๋ จ ์ค์ ์ ๋ชจ์๋๋ ํด๋์ค
RedisCacheConfiguration configuration = RedisCacheConfiguration
.defaultCacheConfig()
// null์ ์บ์ฑ ํ ๊ฒ์ธ์ง
.disableCachingNullValues()
// ๊ธฐ๋ณธ ์บ์ ์ ์ง ์๊ฐ (Time To Live)
.entryTtl(Duration.ofSeconds(10))
// ์บ์๋ฅผ ๊ตฌ๋ถํ๋ ์ ๋์ฌ ์ค์
.computePrefixWith(CacheKeyPrefix.simple())
// ์บ์์ ์ ์ฅํ ๊ฐ์ ์ด๋ป๊ฒ ์ง๋ ฌํ / ์ญ์ง๋ ฌํ ํ ๊ฒ์ธ์ง
.serializeValuesWith(
SerializationPair.fromSerializer(RedisSerializer.java())
);
return RedisCacheManager
.builder(redisConnectionFactory)
.cacheDefaults(configuration)
.build();
}
}
@EnableCaching
// cacheNames: ๋ฉ์๋๋ก ์ธํด์ ๋ง๋ค์ด์ง ์บ์๋ฅผ ์ง์นญํ๋ ์ด๋ฆ
// key: ์บ์์์ ๋ฐ์ดํฐ๋ฅผ ๊ตฌ๋ถํ๊ธฐ ์ํด ํ์ฉํ ๊ฐ
@Cacheable(cacheNames = "itemCache", key = "args[0]")
public ItemDto readOne(Long id) {
log.info("Read One: {}", id);
return repository.findById(id)
.map(ItemDto::fromEntity)
.orElseThrow(()
-> new ResponseStatusException(HttpStatus.NOT_FOUND));
}
@CachePut
@CachePut(cacheNames = "itemCache", key = "#result.id")
public ItemDto create(ItemDto dto) {
return ItemDto.fromEntity(itemRepository.save(Item.builder()
.name(dto.getName())
.description(dto.getDescription())
.price(dto.getPrice())
.stock(dto.getStock())
.build()
));
}
@CacheEvict
@CachePut(cacheNames = "itemCache", key = "args[0]")
@CacheEvict(cacheNames = "itemAllCache", allEntries = true)
public ItemDto update(Long id, ItemDto dto) {
Item item = itemRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
item.setName(dto.getName());
item.setDescription(dto.getDescription());
item.setPrice(dto.getPrice());
item.setStock(dto.getStock());
return ItemDto.fromEntity(itemRepository.save(item));
}